import { createRouter, createWebHistory } from 'vue-router'
import axios from 'axios' // 添加axios导入
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Cart from '../views/Cart.vue'
import EmptyCart from '../views/EmptyCart.vue'
import User from '../views/User.vue'
import ProductDetail from '../views/ProductDetail.vue'
import StoreDetail from '../views/StoreDetail.vue'
import CategoryProducts from '../views/CategoryProducts.vue'
import SearchResults from '../views/SearchResults.vue' // 添加搜索结果页面导入
import AIAssistant from '../views/AIAssistant.vue'
import Orders from '../views/Orders.vue' // 添加订单页面导入
import Wallet from '../views/Wallet.vue' // 添加钱包页面导入
import { TOKEN_KEY } from '../config'

// 后台管理组件
import AdminLayout from '../views/admin/AdminLayout.vue'
import StoreManagement from '../views/admin/StoreManagement.vue'
import UserManagement from '../views/admin/UserManagement.vue'
import OrderManagement from '../views/admin/OrderManagement.vue'
import Dashboard from "@/views/admin/Dashboard.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/cart',
      name: 'Cart',
      component: Cart,
      meta: { requiresAuth: true }
    },
    {
      path: '/empty-cart',
      name: 'EmptyCart',
      component: EmptyCart
    },
    {
      path: '/user',
      name: 'User',
      component: User,
      meta: { requiresAuth: true }
    },
    // 添加订单和钱包路由
    {
      path: '/orders',
      name: 'Orders',
      component: Orders,
      meta: { requiresAuth: true }
    },
    {
      path: '/wallet',
      name: 'Wallet',
      component: Wallet,
      meta: { requiresAuth: true }
    },
    // 后台管理路由
    {
      path: '/admin',
      component: AdminLayout,
      meta: { requiresAuth: true, requiresAdmin: true },
      redirect: '/admin/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'AdminDashboard',
          component: Dashboard
        },
        {
          path: 'stores',
          name: 'AdminStores',
          component: StoreManagement
        },
        {
          path: 'users',
          name: 'AdminUsers',
          component: UserManagement
        },
        {
          path: 'orders',
          name: 'AdminOrders',
          component: OrderManagement
        }
      ]
    },
    // 公开访问的页面 - 不需要登录
    {
      path: '/product/:id',
      name: 'ProductDetail',
      component: ProductDetail
    },
    {
      path: '/store/:id',
      name: 'StoreDetail',
      component: StoreDetail
    },
    {
      path: '/category/:id',
      name: 'CategoryProducts',
      component: CategoryProducts
    },
    {
      path: '/search',
      name: 'SearchResults',
      component: SearchResults
    },
    {
      path: '/ai-assistant',
      name: 'AIAssistant',
      component: AIAssistant
    },
    // 需要登录的页面
    {
      path: '/checkout',
      name: 'Checkout',
      component: () => import('../views/Checkout.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/order/:orderNo',
      name: 'OrderDetail',
      component: () => import('../views/OrderDetail.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/payment/:orderNo',
      name: 'Payment',
      component: () => import('../views/Payment.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/'
    }
  ]
})

// 优化后的全局前置守卫
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem(TOKEN_KEY)

  // 只对标记为需要认证的路由进行验证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      // 没有token，跳转到登录页并保存当前路径
      next({ name: 'Login', query: { redirect: to.fullPath } })
      return
    }

    // 需要管理员权限的路由
    if (to.matched.some(record => record.meta.requiresAdmin)) {
      try {
        const response = await axios.get('/api/user/users/me', {
          headers: { Authorization: `Bearer ${token}` }
        })

        if (response.data.role === 1) {
          next()
        } else {
          console.log('路由守卫 - 非管理员用户，跳转到首页')
          next({ name: 'Home' })
        }
      } catch (error) {
        console.error('路由守卫 - API调用失败:', error)
        // token无效，清除并跳转到登录页
        localStorage.removeItem(TOKEN_KEY)
        localStorage.removeItem('userId')
        localStorage.removeItem('username')
        delete axios.defaults.headers.common['Authorization']
        next({ name: 'Login', query: { redirect: to.fullPath } })
      }
    } else {
      // 普通需要登录的页面，直接放行
      next()
    }
  } else {
    // 不需要认证的路由
    if (token && to.path === '/login') {
      // 已登录用户访问登录页，验证token并重定向
      try {
        const response = await axios.get('/api/user/users/me', {
          headers: { Authorization: `Bearer ${token}` }
        })

        if (response.data.role === 1) {
          next({ name: 'AdminDashboard' })
        } else {
          next({ name: 'Home' })
        }
      } catch (error) {
        // token无效，清除并允许访问登录页
        localStorage.removeItem(TOKEN_KEY)
        localStorage.removeItem('userId')
        localStorage.removeItem('username')
        delete axios.defaults.headers.common['Authorization']
        next()
      }
    } else {
      // 公开页面，直接放行
      next()
    }
  }
})

export default router
